<template>
  <div class="approval-apply">
    <!-- 审批类型选择 -->
    <div class="type-select">
      <el-input
          v-model="searchKey"
          placeholder="搜索审批项"
          style="width: 300px; margin-bottom: 20px"
          clearable
      /><el-button style="margin-bottom: 20px" @click="getApproval()">搜索</el-button>
      <el-button style="margin-bottom: 20px" @click="searchKey='',getApproval()">所有审批项</el-button>

      <el-table
          :data="approvalTypes"
          highlight-current-row
          style="width: 100%;border-radius: 10px"
      >
        <el-table-column prop="id" label="审批项ID" width="320px"></el-table-column>
        <el-table-column prop="processName" label="审批项名" width="180">
          <template #default="{row}">
            <div class="type-tag">
              <el-tag :type="tagTypeMap[row.configData?.approvalItem?.type]">
                {{ labelMap[row.configData?.approvalItem?.type] }}
              </el-tag>
              {{ row.processName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="" label="审批步骤" width="120">
          <template #default="{row}">
            <el-tag>{{ row.configData?.approvalSteps.length }}个步骤</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="" label="提交需求" >
          <template #default="{row}">
            <div style="display: flex; gap: 8px; flex-wrap: wrap;">
              <div
                  v-for="(item, index) in row.configData?.approvalItem?.controls"
                  :key="index"
                  style="position: relative"
              >
                {{ labelMap2[item] }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column>
          <template  #default="{row}"><el-button type="primary" :disabled="isExist(row.configData?.approvalSteps)" style="float: right" @click="startA(row) ">发起审批</el-button></template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 审批表单 -->
    <el-dialog
        v-model="inApproval"
        :title="num.processName"
        width="1000"
        :before-close="handleClose"
    >
      <el-steps style="max-width: 100%;" :active="100">
        <el-step :title="'审批人：'+appUser[index]" :description="'审批要求：'+a.requirement" v-for="(a,index) in num.configData.approvalSteps"></el-step>
      </el-steps>
    <div  class="approval-form">
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
      >
        <el-form-item label="审批事由" prop="title">
          <el-input
              v-model="formData.title"
              placeholder="请输入个人审批情况"
          />
        </el-form-item>

        <!-- 动态表单字段 -->
        <template v-for="(field, index) in num.configData.approvalItem.controls" :key="index">
          <el-form-item
              :label="labelMap2[field]"
              prop="items"
              :rules="formRules"
          >
            <!-- 文本输入 -->
            <el-input
                v-if="field === 'text'"
                v-model="formData.fields.text"
                :placeholder="field.placeholder"
            />

            <!-- 数字输入 -->
            <el-input-number
                v-else-if="field === 'number'"
                v-model="formData.fields.number"
                :precision="field.precision || 0"
                :min="field.min || 0"
            />

            <!-- 日期范围 -->
            <el-date-picker
                v-else-if="field === 'daterange'"
                v-model="formData.fields.daterange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            />

            <!-- 文件上传 -->
            <el-upload
                v-else-if="field === 'file'"
                class="upload-demo"
                :auto-upload="false"
                :on-change="handleFileChange"
                v-model="fileList"
                :show-file-list="true"
                multiple
                style="width: 100%"
                :on-remove="(file, fileList) => handleRemove(file)"
            >
              <el-button type="primary">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip" style="color:rosybrown;">
                  {{ field.tip || '删除文件会直接修改审批信息，请谨慎删除' }}
                </div>
              </template>
            </el-upload>

          </el-form-item>
        </template>

        <el-form-item label="发起审批说明" prop="description">
          <el-input
              v-model="formData.description"
              type="textarea"
              :rows="4"
              placeholder="请输入详细说明"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :disabled="isSub()" @click="submitForm()">立即提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    </el-dialog>
    <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page= "pageCount"
        @change="getApproval"
        class="mt-4"
        style="display: flex; justify-content: center;margin-top: 1vh"
    />
    <!-- 提交成功弹窗 -->
    <el-dialog
        v-model="submitSuccess"
        title="提交成功"
        width="30%"
        :show-close="false"
    >
      <div style="text-align: center">
        <el-icon :size="40" color="#67C23A"><CircleCheckFilled /></el-icon>
        <p style="margin-top: 20px">审批单已成功提交！</p>
        <p>审批编号：{{ currentApprovalId }}</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import {CircleCheckFilled, Document} from '@element-plus/icons-vue'
import UploadInstance, {ElMessage} from "element-plus";
import UploadProps from "element-plus";
import {getApprovals} from "@/api/Approval.js";
import useUserInfoStore from "@/stores/userInfo.js";
import {getUserName} from "@/api/user.js";
import {initiateApproval} from "@/api/AInstance.js";
import {getToken} from "@/api/load.js";
import OSS from 'ali-oss';


// 模拟审批类型数据
const approvalTypes = ref([])

// 表单相关逻辑
const searchKey = ref('')
const selectedType = ref(null)
const userInfo = useUserInfoStore()
const formRef = ref(null)
const submitSuccess = ref(false)
const currentApprovalId = ref('')
const inApproval = ref(false)
const pageCount = ref(0)
const total = ref(1)
const pageSize = ref(4)
const formData = ref({
  title:'',
  description:'',
  fields: {
    daterange: '',
    text:'',
    file:[],
    number:'',
  }
})
const isExist = (names)=>{
  for (let i = 0; i < names.length; i++) {
    if (userInfo.info.id===names[i].approvePeople){
      return true
    }
  }
  return false
}
const isSub=()=>{
  // 第一部分验证
  if (!formData.value.title || !formData.value.description) {
    return true;
  }
  // 第二部分动态字段验证
  return num.value.configData.approvalItem.controls.every(item => {
    // 使用方括号语法访问动态属性
    return String(formData.value.fields[item] || '').trim() === ''
  });
}
const num = ref('')
const options3 = [{value: 1, label: '财务'},{value: 2, label: '人事'},{value: 3, label: '行政'}]
const options4 =  [{value: 'text', label: '文本输入'},{value: 'daterange', label: '时间'},{value: 'file', label: '文件'},{value: 'number', label: '数字'}]

const tagTypeMap = {
  1: 'success',
  2: 'warning',
  3: 'info'
}
const labelMap = Object.fromEntries(
    options3.map(item => [item.value, item.label])
);
const labelMap2 = Object.fromEntries(
    options4.map(item => [item.value, item.label])
);
const getApproval = async () => {
  // if (pageCount!==1){
  //   pageCount.value = Math.ceil(total.value/pageSize.value)
  // }
  let res = await getApprovals(searchKey.value,userInfo.info.enterpriseId,pageCount.value,pageSize.value)
  if (res.total!==undefined) {
    total.value = res.total
  }
  approvalTypes.value = res.list
  if (approvalTypes.value !== undefined){
    for (let i = 0; i < approvalTypes.value.length; i++) {
      approvalTypes.value[i].configData = JSON.parse(approvalTypes.value[i].configData)
    }
  }
}


// 文件列表（响应式）
const fileList = ref([])


const getSTSToken = async () => {
  let res = await getToken();
  return res;
};

const initOSSClient = async () => {
  let credentials = await getSTSToken();
  return new OSS({
    region: 'oss-cn-hangzhou',
    accessKeyId: credentials.AccessKeyId,
    accessKeySecret: credentials.AccessKeySecret,
    stsToken: credentials.SecurityToken,
    bucket: 'web-framework10011',
    endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
    secure: true
  });}
// 文件上传处理
const handleFileChange = async (uploadFile) => {
  try {
    const client = await initOSSClient()
    const ossPath = `在线审批系统/${uploadFile.raw.uid}_${uploadFile.name}`

    // 执行上传
    const result = await client.put(ossPath, uploadFile.raw)

    // 更新文件列表
    fileList.value.push({
      name: ossPath,  // 存储完整OSS路径
      url: result.url,
      raw: uploadFile.raw
    })
    ElMessage.success('上传成功')
  } catch (err) {
    ElMessage.error('上传失败')
    console.error('OSS Error:', err)
  }
}

// 文件删除
const handleRemove = async (file) => {
  try {
    file.name = `在线审批系统/${file.raw.uid}_${file.name}`
    const client = await initOSSClient()
    await client.delete(file.name)
    console.log(file)
    // 更新文件列表
    fileList.value = fileList.value.filter(f => f.uid !== file.uid)
    ElMessage.success('删除成功')
  } catch (err) {
    ElMessage.error('删除失败')
    console.error('Delete Error:', err)
  }
}



// 表单验证规则
const formRules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  description: [{ required: true, message: '请输入说明', trigger: 'blur' }],
})



// 提交表单
const submitForm = async () => {
  formData.value.fields.file = fileList.value
  let res = await initiateApproval(userInfo.info.id,num.value.id,formData.value)
  if (res==='发起成功') {
    ElMessage.success(res)
    num.value = ''
    inApproval.value = false
  }else {
    ElMessage.error('发起失败')
  }
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  selectedType.value = null
  formData.value.fields={}
}

let appUser = ref([])
const startA =async (row) => {
  num.value = row;
  for (let i = 0; i < num.value.configData.approvalSteps.length; i++) {
    await getUserName(num.value.configData.approvalSteps[i]?.approvePeople).then(result => {
      appUser.value[i] = num.value.configData.approvalSteps[i]?.approveType + "/" + result
    })
  }
  inApproval.value = true;
  console.log(num.value )
}

getApproval()

</script>

<style scoped>
.approval-apply {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.type-tag {
  display: flex;
  align-items: center;
  gap: 10px;
}

.approval-form {
  margin-top: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.el-upload__tip {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}
</style>